
// Definition for a binary tree node.
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

/**
 * @param {TreeNode} root
 * @return {number}
 */
function createTree(arr) {
  let nodeArr = [];
  for(let i = 0; i < arr.length; i++) {
    let node = new TreeNode(arr[i]);
    nodeArr.push(node);
  }
  for(let i = 0; i < nodeArr.length; i++) {
    if(2 * i + 1 < nodeArr.length) {
      nodeArr[i].left = nodeArr[2 * i + 1];
    }
    if(2 * i + 2 < nodeArr.length) {
      nodeArr[i].right = nodeArr[2 * i + 2];
    }
  }
  return nodeArr[0];
}
var findTilt = function(root) {
  if(!root || (!root.left && !root.right)) return 0;
  let result = 0;
  function computeAll(node) {
    if(!node) return 0;
    if(node.left && node.right) {
      return node.val + computeAll(node.left) + computeAll(node.right);
    } else if(node.left) {
      return node.val + computeAll(node.left);
    } else if(node.right) {
      return node.val + computeAll(node.right)
    } else {
      return node.val;
    }
  }
  function preView(node) {
    if(!node) return;
    let num = Math.abs(computeAll(node.left, node.val) - computeAll(node.right, node.val))
    result += num;
    preView(node.left);
    preView(node.right);
  }
  preView(root);
  return result;
};
let root = [1,2,3];
console.log(findTilt(createTree(root)));
root = [4,2,9,3,5,null,7];
console.log(findTilt(createTree(root)));
root = [21,7,14,1,1,2,2,3,3];
console.log(findTilt(createTree(root)));
